package ddz.db.redis;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.ScanParams;
import redis.clients.jedis.ScanResult;

import java.util.HashSet;
import java.util.Set;

abstract public class AbsRedis implements IRedis {

    private int redisScanCount = 100;

    public int getRedisScanCount() {
        return redisScanCount;
    }

    public void setRedisScanCount(int redisScanCount) {
        this.redisScanCount = redisScanCount;
    }

    protected Set<byte[]> scanKeys(Jedis jedis, byte[] pattern) {
        Set<byte[]> keys = new HashSet<>();
        ScanParams params = new ScanParams();
        params.count(redisScanCount);
        params.match(pattern);
        byte[] cursor = ScanParams.SCAN_POINTER_START_BINARY;
        ScanResult<byte[]> scanResult;
        do {
            scanResult = jedis.scan(cursor, params);
            keys.addAll(scanResult.getResult());
            cursor = scanResult.getCursorAsBytes();
        } while (scanResult.getStringCursor().compareTo(ScanParams.SCAN_POINTER_START) > 0);
        return keys;
    }
}
